package com.ctg.sysmgr.sso.server.common.uitl;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;

public class StringToTimeStampUtil {
	private static final String DEFAULT_PATTERN = "yyyyMMddHHmmss";

	
	/**
	 * 支持以下格式转换成timestamp：
	 * yyyyMMddHHmmss、yyyy-MM-dd HH:mm:ss 、MM/dd/yyyy HH:mm:ss、yyyy-MM-dd、MM/dd/yyyy
	 * @param timeStr
	 * @param pattern
	 * @return
	 */
	public static Timestamp str2Timestamp(String timeStr,String pattern) {
		Timestamp result = null;
		if (timeStr == null) {
			return null;
		}
		 if (pattern != null && !"".equals(pattern)) {
			 //如果模板不等于以下其中一种，则抛出异常
			 if (!"yyyyMMddHHmmss".equals(pattern)
			 && !"yyyy-MM-dd HH:mm:ss".equals(pattern)
			 && !"MM/dd/yyyy HH:mm:ss".equals(pattern)
			 && !"yyyy-MM-dd".equals(pattern)
			 && !"MM/dd/yyyy".equals(pattern)) {
				 throw new IllegalArgumentException("Date format ["+pattern+"] is invalid");
			 }
		 }else{
			 pattern = DEFAULT_PATTERN;//
		 }

		Date d = null;
		SimpleDateFormat sdf = new SimpleDateFormat(pattern);
		try {
			d = sdf.parse(timeStr);
			result = new Timestamp(d.getTime());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	public static void main(String[] args) {
		System.out.println(str2Timestamp("2014-12-12 12:12:12","yyyy-MM-dd HH:mm:ss"));
	}
}
